package com.cljz.makepassenger.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.InputFilter;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cljz.makepassenger.R;
import com.cljz.makepassenger.base.App;
import com.cljz.makepassenger.base.BaseActivity;
import com.cljz.makepassenger.model.net.bean.ThirdLoginBindData;
import com.cljz.makepassenger.present.activity.BindPhoneP;
import com.cljz.makepassenger.utils.CommonUtils;
import com.cljz.makepassenger.utils.T;
import com.jakewharton.rxbinding.view.RxView;
import com.jakewharton.rxbinding.widget.RxTextView;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import cn.droidlover.xdroidmvp.router.Router;
import rx.functions.Action1;

/**
 * Created by apple on 2017/4/5.
 */

public class BindPhoneActivity extends BaseActivity<BindPhoneP> {


    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.ll_message)
    LinearLayout llMessage;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.bt_get_code)
    Button btGetCode;
    @BindView(R.id.activity_bind)
    LinearLayout activityBind;
    @BindView(R.id.fl_back)
    FrameLayout flBack;
    @BindView(R.id.tv_title_name)
    TextView tvTitleName;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    private String user_from;
    private String openid;
    private String unionid;
    private boolean isLogin = false;            //获取验证码为false，登录为true
    private Bundle bundle;

    private TimeCount timeCount;
    private Animation outToLeft;
    private Animation inFromRight;
    private Animation outToRight;
    private Animation inFromLeft;


    @Override
    public void initData(Bundle savedInstanceState) {
        tvTitleName.setText("绑定手机");
        bundle = new Bundle();
        Intent intent = getIntent();
        user_from = intent.getStringExtra("user_from");
        openid = intent.getStringExtra("openid");
        unionid = intent.getStringExtra("unionid");
        timeCount = new TimeCount(60000, 1000);
        outToLeft = AnimationUtils.loadAnimation(App.getInstance(), R.anim.out_to_left);
        inFromRight = AnimationUtils.loadAnimation(App.getInstance(), R.anim.in_from_right);
        outToRight = AnimationUtils.loadAnimation(App.getInstance(), R.anim.out_to_right);
        inFromLeft = AnimationUtils.loadAnimation(App.getInstance(), R.anim.in_from_left);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_bind_phone;
    }

    @Override
    public BindPhoneP newP() {
        return new BindPhoneP();
    }

    @Override
    protected void initListener() {
        super.initListener();
        RxTextView.textChanges(etPhone)
                .compose(this.<CharSequence>bindToLifecycle())
                .subscribe(new Action1<CharSequence>() {
                    @Override
                    public void call(CharSequence charSequence) {
                        if (isLogin) {
                            if (charSequence.length() == 6) {
                                btGetCode.setEnabled(true);
                            } else {
                                btGetCode.setEnabled(false);
                            }
                        } else {
                            if (CommonUtils.checkPhone(charSequence.toString())) {
                                btGetCode.setEnabled(true);
                                btGetCode.setText("获取验证码");
                            } else {
                                btGetCode.setEnabled(false);
                                btGetCode.setText("登录");
                            }
                        }
                    }
                });
        RxView.clicks(btGetCode).
                compose(this.<Void>bindToLifecycle())
                .throttleFirst(1, TimeUnit.SECONDS).subscribe(new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                showLoadingDialog();
                if (isLogin) {
                    String code = etPhone.getText().toString().trim();
                    getP().loginBind(bundle.getString("phone"), user_from, openid, unionid, code);
                } else {
                    String phone = etPhone.getText().toString().trim();
                    bundle.putString("phone", phone);
                    getP().getCode(phone);
                }
            }
        });
        RxView.clicks(flBack)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(1, TimeUnit.SECONDS).subscribe(new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                if (isLogin) {
                    isLogin = false;
                    changeState();
                } else {
                    Router.newIntent((Activity) App.getInstance())
                            .to(LoginActivity.class)
                            .data(new Bundle())
                            .launch();
                    Router.pop(BindPhoneActivity.this);
                }
            }
        });
    }

    public void getSmsFail(String err) {
        dismissLoadingDialog();
        T.getInstance().showShort(err);
    }

    public void getSmsSucceed() {
        dismissLoadingDialog();
        isLogin = true;
        changeState();
    }


    public void getBindFail(String err) {
        dismissLoadingDialog();
        T.getInstance().showShort(err);
    }

    public void getBindSucceed(ThirdLoginBindData thirdLoginBindData) {
        dismissLoadingDialog();
        T.getInstance().showShort("绑定成功");
//        Router.newIntent((Activity) App.getInstance())
//                .to(GroupListActivity.class)
//                .data(new Bundle())
//                .launch();
        Router.newIntent((Activity) App.getInstance())
                .to(MainActivity.class)
                .data(new Bundle())
                .launch();
        Router.pop(this);
    }

    public void changeState() {
        if (isLogin) {
            activityBind.startAnimation(outToLeft);
            activityBind.startAnimation(inFromRight);
            tvTime.setVisibility(View.VISIBLE);
            etPhone.setText("");
            etPhone.setHint("请输入验证码");
            etPhone.setMaxLines(6);
            etPhone.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)});
            btGetCode.setText("登录");
            timeCount.start();
            llMessage.setVisibility(View.VISIBLE);
        } else {
            activityBind.startAnimation(outToRight);
            activityBind.startAnimation(inFromLeft);
            etPhone.setMaxLines(11);
            etPhone.setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)});
            tvTime.setVisibility(View.INVISIBLE);
            etPhone.setHint("请输入手机号验证登录");
            etPhone.setText(bundle.getString("phone"));
            btGetCode.setText("获取验证码");
            llMessage.setVisibility(View.GONE);
        }
    }

    private class TimeCount extends CountDownTimer {

        TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long l) {
            tvTime.setText(l / 1000 + "s");
        }

        @Override
        public void onFinish() {
            isLogin = false;
            changeState();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timeCount.cancel();
        timeCount = null;
    }
}
